import jsonwebtoken from 'jsonwebtoken'

/**
 * JWT认证中间件
 * 验证Authorization header中的JWT token并提取用户信息
 */
export const jwtAuth = async (ctx, next) => {
  try {
    const authHeader = ctx.headers.authorization
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      ctx.status = 401
      ctx.body = {
        success: false,
        error: '缺少认证token'
      }
      return
    }

    const token = authHeader.substring(7) // 移除 "Bearer " 前缀
    const decoded = jsonwebtoken.verify(token, process.env.JWT_SEED)
    
    // 将用户信息添加到ctx.state中供后续中间件使用
    ctx.state.user = {
      sgsToken: decoded.sgsToken,
      username: decoded.uname,
      email: decoded.email,
      role: decoded.role || 'user', // 默认为普通用户
      locationName: decoded.locationName,
      locationCode: decoded.locationCode,
      labCode: decoded.labCode,
      labName: decoded.labName
    }
    
    await next()
  } catch (error) {
    console.error('JWT验证失败:', error.message)
    ctx.status = 401
    ctx.body = {
      success: false,
      error: 'Token无效或已过期'
    }
  }
}

/**
 * 可选的JWT认证中间件
 * 如果有token则验证，没有token则继续执行但不设置用户信息
 */
export const optionalJwtAuth = async (ctx, next) => {
  try {
    const authHeader = ctx.headers.authorization
    if (authHeader && authHeader.startsWith('Bearer ')) {
      const token = authHeader.substring(7)
      const decoded = jsonwebtoken.verify(token, process.env.JWT_SEED)
      
      ctx.state.user = {
        sgsToken: decoded.sgsToken,
        username: decoded.uname,
        email: decoded.email,
        role: decoded.role || 'user', // 默认为普通用户
        locationName: decoded.locationName,
        locationCode: decoded.locationCode,
        labCode: decoded.labCode,
        labName: decoded.labName
      }
    }
    
    await next()
  } catch (error) {
    console.warn('JWT验证警告:', error.message)
    // 继续执行，但不设置用户信息
    await next()
  }
}

/**
 * 管理员权限验证中间件
 * 需要先通过jwtAuth中间件验证身份
 * 支持三级权限系统：user, admin, system
 */
export const requireAdmin = async (ctx, next) => {
  if (!ctx.state.user) {
    ctx.status = 401
    ctx.body = {
      success: false,
      error: '需要登录'
    }
    return
  }

  // 允许 admin 和 system 角色访问管理功能
  if (ctx.state.user.role !== 'admin' && ctx.state.user.role !== 'system') {
    ctx.status = 403
    ctx.body = {
      success: false,
      error: '需要管理员权限'
    }
    return
  }

  await next()
}

/**
 * 系统权限验证中间件
 * 只允许系统权限用户访问
 */
export const requireSystemAdmin = async (ctx, next) => {
  if (!ctx.state.user) {
    ctx.status = 401
    ctx.body = {
      success: false,
      error: '需要登录'
    }
    return
  }

  if (ctx.state.user.role !== 'system') {
    ctx.status = 403
    ctx.body = {
      success: false,
      error: '需要系统权限'
    }
    return
  }

  await next()
}